﻿using UnityEngine;
using System.Collections.Generic;

public class ObjectPool : MonoBehaviour {
	// What prefab the object pool will use
	public GameObject prefab;
	public int preloadCount; // How many to preload
	Stack<GameObject> idlePool;
	List<GameObject> activePool;
	// Use this for initialization
	void Start () {
		idlePool = new Stack<GameObject> ();
		activePool = new List<GameObject> ();
		for(int i = 0; i < preloadCount; i++) {
			idlePool.Push((GameObject)Instantiate (prefab, transform.position, Quaternion.identity));
			idlePool.Peek().renderer.enabled = false;
			if(idlePool.Peek ().GetComponent<ShipAttributes>() != null) {
				idlePool.Peek ().GetComponent<ShipAttributes>().setObjectPool(this);
			}
			idlePool.Peek().SetActive(false);
		}
	}

	public GameObject spawnFromPool() {
		if(idlePool.Count > 0) {
			idlePool.Peek ().renderer.enabled = true;
			idlePool.Peek ().SetActive (true);
			activePool.Add (idlePool.Peek ());
			return idlePool.Pop();
		} else {
			return null;
		}
	}

	public void pushToPool(GameObject gameObject) {
		idlePool.Push (gameObject);
		gameObject.renderer.enabled = false;
		gameObject.SetActive (false);
		for(int i = 0; i < activePool.Count; i++) {
			if(gameObject == activePool[i]) {
				activePool.Remove (gameObject);
				break;
			}
		}
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}
